package com.nf.mvc.view;

import com.nf.mvc.ViewResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class RedirectViewResult extends ViewResult {

    private String url;
    private final Map<String, String> model;

    public RedirectViewResult(String url) {
        this(url, new HashMap<>());
    }

    public RedirectViewResult(String url, Map<String, String> model) {
        this.url = url;
        this.model = model;
    }

    @Override
    public void render(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        this.url += initModel();
        resp.sendRedirect(url);
    }

    private String initModel() {
        // url?a=10&b=20
        if (model.isEmpty()) {
            return "";
        }
        // 见StringJoiner的注释理解其分隔符，前后缀的含义
        return model.entrySet().stream()
                .map(entry -> entry.getKey() + "=" + entry.getValue())
                .collect(Collectors.joining("&", "?", ""));
    }
}
